package com.cloud.sso.service;

import com.cloud.sso.common.exception.AppException;
import com.cloud.sso.common.page.AppPageInfo;
import com.cloud.sso.common.util.CollectionUtil;
import com.cloud.sso.dto.OrgQueryDto;
import com.cloud.sso.dto.OrgSaveDto;
import com.cloud.sso.entity.SysOrg;
import com.cloud.sso.mapper.OrgMapper;
import com.cloud.sso.vo.OrgVo;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Service
public class OrgService {


    @Autowired
    private OrgMapper orgMapper;

    @Autowired
    private UserService userService;

    /**
     * 分页查询组织信息
     *
     * @param queryDto
     * @return
     */
    public AppPageInfo queryByPage(OrgQueryDto queryDto) {

        //计算分页相关属性
        queryDto.setStartIndex();

        List<SysOrg> orgList = orgMapper.queryByPage(queryDto);
        Integer count = orgMapper.getCount(queryDto);
        AppPageInfo pageInfo = new AppPageInfo(orgList, count, queryDto.getPageNum(), queryDto.getPageSize());

        return pageInfo;
    }

    /**
     * 查询根组织节点
     *
     * @return
     */
    public List<OrgVo> rootOrg() {
        return entityToVo(orgMapper.queryRootOrg());
    }

    /**
     * 查询直接下级
     *
     * @param orgId
     * @return
     */
    public List<OrgVo> subOrg(String orgId) {
        return entityToVo(orgMapper.querySubOrg(orgId));
    }

    /**
     * 查询组织详情
     *
     * @param id
     * @return
     */
    public SysOrg get(String id) {
        return orgMapper.selectById(id);
    }

    /**
     * 查询直接下级组织
     *
     * @param orgId
     * @return
     */
    public List<SysOrg> querySubOrg(String orgId) {
        return orgMapper.querySubOrg(orgId);
    }

    /**
     * 保存组织
     *
     * @param orgSaveDto
     */
    public void save(OrgSaveDto orgSaveDto) {
        SysOrg sysOrg = new SysOrg();
        BeanUtils.copyProperties(orgSaveDto, sysOrg);

       try{
           if (sysOrg.getId() == null) {
               sysOrg.setOrgCode(getCode(orgSaveDto.getParentId()));
               orgMapper.insert(sysOrg);
           } else {
               //如果上级组织发生变化，重新计算orgCode
               SysOrg originOrg = orgMapper.selectById(orgSaveDto.getId());
               if (!orgSaveDto.getParentId().equals(originOrg.getParentId())) {
                   sysOrg.setOrgCode(getCode(orgSaveDto.getParentId()));
               }
               orgMapper.updateById(sysOrg);
           }
       }catch (Exception e){
           e.printStackTrace();
           throw new AppException(e.getMessage());
       }

    }

    /**
     * 动态计算组织code
     *
     * @param parentId
     * @return
     */
    public String getCode(String parentId) {

        if (parentId == null) {
            throw new AppException("上级组织id不能为空");
        }

        SysOrg parentOrg = orgMapper.selectById(parentId);
        if (parentOrg == null) {
            throw new AppException("找不到上级组织");
        }

        String parentCode = parentOrg.getOrgCode();

        List<SysOrg> orgList = orgMapper.querySubOrg(parentId);
        if (orgList == null || orgList.size() == 0) {
            return parentCode + "0001";
        }

        String maxCode = orgList.stream().filter(e -> e != null).max(new Comparator<SysOrg>() {
            @Override
            public int compare(SysOrg o1, SysOrg o2) {
                //String o1Code = o1.getOrgCode().replace(parentCode, "");
             //   String o1Code = o1.getOrgCode().substring(o1.getOrgCode().length()-parentCode.length(), o1.getOrgCode().length());
             //   String o2Code = o2.getOrgCode().replace(parentCode, "");
                return Integer.parseInt(o1.getOrgCode()) > Integer.parseInt(o2.getOrgCode()) ? 1 : -1;
            }
        }).orElse(null).getOrgCode();

        if (maxCode == null) {
            throw new AppException("获取code失败");
        }

        String code = String.format("%04d", Integer.parseInt(maxCode.replace(parentCode, "")) + 1);

        return new StringBuilder(parentCode).append(code).toString();
    }

    /**
     * 删除组织
     *
     * @param id
     */
    public void deleteOrg(String id) {
        SysOrg sysOrg = orgMapper.selectById(id);
        if (sysOrg == null) {
            throw new AppException("要删除的组织不存在");
        }
        List<SysOrg> orgList = orgMapper.querySubOrg(id);
        if (CollectionUtil.isNotNull(orgList)) {
            throw new AppException("请先删除下级组织");
        }
        if (CollectionUtil.isNotNull(userService.listByOrg(id))) {
            throw new AppException("请先删除组织下的人员");
        }

        orgMapper.deleteById(id);

    }

    public List<OrgVo> entityToVo(List<SysOrg> orgList) {
        List<OrgVo> orgVos = new ArrayList<>();

        for (SysOrg org : orgList) {
            OrgVo orgVo = new OrgVo();

            BeanUtils.copyProperties(org, orgVo);
            orgVo.setOrgId(org.getId());
            orgVo.setLeaf(org.getLeaf().equals("1") ? true : false);

            orgVos.add(orgVo);
        }

        return orgVos;
    }

}
